<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="900px">
    <div class="dialogContent">
      <el-form
        ref="form"
        :disabled="viewType !== 'add' && viewType !== 'edit' && viewType !== 'copy'"
        label-width="160px"
        :rules="rules"
        size="mini"
        :model="data"
      >
        <div class="divider" style></div>
        <el-form-item label="申请人：">
          <span>{{data.applyName}}</span>
        </el-form-item>
        <el-form-item label="发券主体：">
          <el-radio-group v-model="data.provider" :disabled="status === 3 && viewType === 'edit'">
            <el-radio :label="0">平台</el-radio>
            <el-radio :label="1">商家</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="费用归属：" prop="couponsCostDtos">
          <div v-for="(item,index) in data.couponsCostDtos" :key="index">
            <el-select :disabled="status === 3 && viewType === 'edit'" style="margin-right: 10px;" class="addconfig-input" v-model="item.type">
              <el-option label="便捷青岛" :value="0" v-if="data.provider === 0"></el-option>
              <el-option label="商家" :value="1"></el-option>
            </el-select>
            <el-input
              clearable
              placeholder="百分比"
              v-model="item.costRatio"
              disabled
              style="width: 200px; vertical-align: 'middle';"
            >
              <template slot="prepend">比例</template>
              <template slot="append">%</template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="发券方式：" prop="providedType">
          <el-select :disabled="status === 3 && viewType === 'edit'" class="addconfig-input" v-model="data.providedType">
            <el-option label="定向发放" :value="0"></el-option>
            <el-option label="非定向发放" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券批次名称：" prop="batchName">
          <el-input
            clearable
            placeholder="请输入批次名称"
            v-model="data.batchName"
            maxlength="50"
            class="addconfig-input"
          ></el-input>
        </el-form-item>
        <div class="divider" style></div>
        <el-form-item label="优惠券使用类型：" prop="batchType">
          <el-select :disabled="status === 3 && viewType === 'edit'" class="addconfig-input" v-model="data.batchType">
            <el-option label="请选择" value></el-option>
            <el-option label="现金券" :value="0"></el-option>
            <el-option label="满减券" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券金额（元）：" prop="batchMoney">
          <el-input-number
            clearable
            placeholder="请输入正数，支持两位小数"
            :min="0"
             :disabled="status === 3 && viewType === 'edit'"
            :precision="2"
            :controls="false"
            v-model="data.batchMoney"
            class="addconfig-input"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="优惠券限额（元）：" prop="limitMoney" v-if="data.batchType === 1">
          <el-input-number
            placeholder="请输入正数，支持两位小数"
            :min="0"
            :precision="2"
             :disabled="status === 3 && viewType === 'edit'"
            :controls="false"
            v-model="data.limitMoney"
            class="addconfig-input"
          ></el-input-number>
        </el-form-item>
        <div class="divider" style></div>
        <el-form-item label="使用场景限制：" prop="onlineFlag">
          <el-checkbox-group v-model="data.onlineFlag">
            <el-checkbox :label="0">线上</el-checkbox>
            <el-checkbox :label="1">线下</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="使用商户限制：" prop="currentUsingId">
          <el-radio-group :disabled="status === 3 && viewType === 'edit'" style="margin-right: 10px;" v-model="data.rangeType">
            <el-radio :label="0" :disabled="true">全平台</el-radio>
            <el-radio :label="2">限商户</el-radio>
          </el-radio-group>
          <el-select :disabled="status === 3 && viewType === 'edit'" placeholder="请选择" v-model="data.currentUsingId" v-if="data.rangeType === 2">
            <!-- <el-option label="请选择" value></el-option> -->
            <el-option
              v-for="item in merchantList"
              :key="item.merchantId"
              :label="item.merchantName"
              :value="item.merchantId"
            ></el-option>
            <!-- <el-option label="App" :value="1"></el-option>
            <el-option label="H5" :value="2"></el-option>-->
          </el-select>
        </el-form-item>
        <el-form-item label="前端展示标题：" prop="showTitle">
          <el-input
            placeholder="前端展示标题"
            class="addconfig-input"
            maxlength="20"
            v-model="data.showTitle"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="限制使用说明：">
          <el-input type="textarea" maxlength="100" v-model="data.usedDes"></el-input>
        </el-form-item>
        <div class="divider" style></div>
        <el-form-item label="有效期限制类型：" prop="timeLimit">
          <el-select class="addconfig-input" v-model="data.timeLimit" :disabled="status === 3 && viewType === 'edit'">
            <el-option label="绝对日期" :value="0"></el-option>
            <el-option label="相对日期" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="有效期："
          class="effectiveStartAndEndTime"
          prop="time"
          v-if="data.timeLimit === 0"
        >
          <el-date-picker
           :disabled="status === 3 && viewType === 'edit'"
            v-model="data.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item v-else label="有效期：" prop="relativeTime">
          <el-input-number :disabled="status === 3 && viewType === 'edit'" v-model="data.relativeTime" :min="0" :controls="false" :precision="0"></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="相对有效期" v-if="data.timeLimit === 1">
        <el-input placeholder="请输入相对有效期" v-model="data.relativeTime" class="addconfig-input"></el-input>
        </el-form-item>-->
        <el-form-item label="申请数量：" prop="applicateNum">
          <el-input-number
           :disabled="status === 3 && viewType === 'edit'"
            :min="0"
            :precision="0"
            :controls="false"
            placeholder="请输入合理数量"
            v-model="data.applicateNum"
            class="addconfig-input"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="每人最大可领取数量：">
          <el-input-number
           :disabled="status === 3 && viewType === 'edit'"
            :min="0"
            :precision="0"
            :controls="false"
            placeholder="请输入正整数"
            v-model="data.limitNum"
            class="addconfig-input"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="预警数量：">
          <el-input-number
            :min="0"
            :precision="0"
            :controls="false"
            placeholder="请输入正整数"
            class="addconfig-input"
            v-model="data.warningNum"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否到期预警：">
          <el-radio-group v-model="data.expirationNotice">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否发送短信：">
          <el-radio-group :disabled="data.expirationNotice !== 1" v-model="data.smsFlag">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否推送AppPush：">
          <el-radio-group
            style="margin-right: 20px;"
            :disabled="data.expirationNotice !== 1"
            v-model="data.pushFlag"
          >
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
          <el-input
            placeholder="请输入AppPush内容"
            v-model="data.smsDes"
            style="width: 300px;"
            :disabled="disabledSmsContent"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        @click="submit"
        v-if="viewType === 'add' || viewType === 'edit' || viewType === 'copy'"
      >保 存</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getCouponDetail,
  addCoupon,
  getMerchant,
  editCoupon,
} from "@/api/coupon";
import { getStatusNameByStatus } from "@/utils/status";
import { validate, dateFormat } from "@/utils";

function validatorDtos(rule, value, cb) {
  cb();
}

function validatorTime(rule, value, cb) {
  if (!value || !value.length) {
    cb(new Error("有效期不能为空"));
  } else if (value[0] === value[1]) {
    cb(new Error("开始时间与结束时间不能相同"));
  } else {
    cb();
  }
}

function validatorFlag(rule, value, cb) {
  if (!value || !value.length) {
    cb(new Error("使用场景不能为空！"));
  } else {
    cb();
  }
}

export default {
  name: "coupon-dialog",
  data() {
    return {
      // 用于控制窗体的显示与隐藏
      dialogVisible: false,
      // 用于标识当前窗体的类别
      viewType: "add",
      merchantList: [],
      rangeTypeSelect: 1,
      couponId: "",
      status: '',
      rules: {
        batchName: [
          {
            required: true,
            message: "优惠券批次名称不能为空!",
            trigger: "blur",
          },
        ],
        batchType: [
          {
            required: true,
            message: "请选择优惠券使用类型!",
            trigger: "change",
          },
        ],
        batchMoney: [
          { required: true, message: "优惠券金额不能为空!", trigger: "blur" },
        ],
        limitMoney: [
          { required: true, message: "优惠券限额不能为空!", trigger: "blur" },
          {
            required: true,
            validator: (rule, value, cb) => {
              if (this.data.batchType === 1 && value < this.data.batchMoney) {
                cb(new Error("满减券使用类型优惠券金额需大于等于优惠券金额!"));
              } else {
                cb();
              }
            },
            trigger: "blur",
          },
        ],
        // 使用场景限制
        onlineFlag: [
          {
            required: true,
            validator: validatorFlag,
            trigger: "click",
          },
        ],
        showTitle: [
          { required: true, message: "前端展示标题不能为空!", trigger: "blur" },
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (value.length > 20) {
                return callback(new Error("前端展示标题长度不能超过50以内！"));
              }
              if (!validate(value)) {
                return callback(
                  new Error("前端展示标题只能填写字母、数字或字符串！")
                );
              }
              callback();
            },
          },
        ],
        applicateNum: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (!value || value === "") {
                callback(new Error("申请数量不能为空"));
              } else if (parseInt(value) === 0) {
                callback(new Error("申请数量不能为0"));
              } else {
                callback();
              }
            },
          },
        ],
        time: [{ required: true, trigger: "change", validator: validatorTime }],
        relativeTime: [
          { required: true, trigger: "blur", message: "请输入有效期！" },
          { required: true, trigger: "blur", validator: (rule, value, callback)=>{
            if (!isNaN(value) && value === 0) {
              callback(new Error("相对有效期不能为0"));
            } else {
              callback();
            }
          }}
        ],
        costRatio: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("费用比例不能为空！"));
              }
              if (value !== "100") {
                callback(new Error("费用比例必须为100"));
              }

              if (
                this.data.couponsCostDtos.costRatio !== "" &&
                this.data.couponsCostDtos.costRatio === "100"
              ) {
                this.$refs.form.validateField("costRatio");
              }
            },
            trigger: "blur",
          },
        ],
        providedType: [
          { required: true, message: "发放方式不能为空!", trigger: "blur" },
        ],
        couponsCostDtosType: [
          { required: true, message: "费用归属不能为空!", trigger: "blur" },
        ],
        // 使用商户限制
        currentUsingId: [
          {
            required: true,
            message: "使用商户限制至少选一个!",
            trigger: "blur",
          },
          {
            required: true,
            message: "使用商户限制至少选一个!",
            trigger: "change",
          },
        ],
        timeLimit: [{ required: true, message: "请选择有效期限制类型!" }],
        // 有效期
        effectiveStartAndEndTime: [
          { required: true, message: "请选择有效期限制类型!" },
        ],
      },
      pickerOptions: {
        disabledDate: (time) => {
          const now = new Date();
          now.setDate(now.getDate() - 1);

          return time.getTime() < now.getTime();
        },
      },
      data: {
        time: [],
        provider: 0,
        couponsCostDtos: [{ costRatio: 100, type: 0 }],
        // 申请人名称
        applyName: "广电测试",
        // 发券方式
        providedType: 0,
        // 优惠券批次名称
        batchName: "",
        // 优惠券使用类型
        batchType: "",
        // 优惠券金额
        batchMoney: 0,
        // 优惠券限额
        limitMoney: 0,
        relativeTime: 0,
        // // 使用场景限制 是否支持线上使用（0 否 1是）
        // onlineFlag: "0",
        // // 使用场景限制 是否支持线下使用（0 否 1是）
        // offlineFlag: "0",
        // 使用场景限制
        onlineFlag: [0],
        // 使用平台限制(0全平台 1app 2 H5)
        rangeType: 2,
        supportType: "",
        // 前端展示标题
        showTitle: "",
        // 使用限制说明
        usedDes: "",
        // 有效期限制类型(0 绝对日期 1相对日期)
        timeLimit: 0,
        // 有效期开始时间
        startTime: "",
        // 有效期结束时间
        endTime: "",
        effectiveStartAndEndTime: "",
        // 相对有效期
        relativeTime: "",
        // 申请数量
        applicateNum: undefined,
        // 每人最大可领取数量
        limitNum: undefined,
        // 预警数量
        warningNum: undefined,
        // 是否到期预警 （0 否 1是）
        expirationNotice: 0,
        // 到期预警发短信flag(0 不发短信 1发短信)
        smsFlag: "",
        // 到期提醒是否发送appPush（0 不发生 1发送）
        pushFlag: "",
        // 推送内容
        smsDes: "",
        // 当前选中的商户id
        // 通过与张宇飞沟通 发现商户id后续单选或多选目前不确定 暂定为单选
        currentUsingId: "",
      },
    };
  },
  computed: {
    disabledSmsContent() {
      return !(
        this.data.expirationNotice === 1 &&
        (this.data.smsFlag === 1 || this.data.pushFlag === 1)
      );
    },
    dialogTitle() {
      let title = "";
      switch (this.viewType) {
        case "add":
          title = "新增配置";
          break;
        case "edit":
          title = "修改配置";
          break;
        case "detail":
          title = "查看详情";
          break;
        case "copy":
          title = "复制配置";
          break;
      }
      return title;
    },
  },
  watch: {
    "data.time"(val) {
      if (!val || !val.length) {
        this.data.startTime = "";
        this.data.endTime = "";
      } else {
        this.data.startTime = val[0];
        this.data.endTime = val[1];
      }
    },
    "data.provider"(val) {
      this.data.couponsCostDtos[0].type = val;
    },
  },
  methods: {
    // 查询商家
    async getMerchantList() {
      // 后端接口是直接返回的数据列表
      // 没有在外层包裹code以及message等字段
      const res = await getMerchant();
      this.merchantList = res.filter((item) => {
        return item.merchantId !== "0";
      });
    },
    submit() {
      this.viewType === "edit" ? this.save() : this.addCoupon();
    },
    /**
     * 新增配置时的保存操作
     */
    addCoupon() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;
        const params = {
          provider: this.data.provider,
          providedType: this.data.providedType,
          batchName: this.data.batchName,
          batchType: this.data.batchType,
          batchMoney: this.data.batchMoney,
          limitMoney: this.data.limitMoney,
          onlineFlag: this.data.onlineFlag.includes(0) ? 1 : 0,
          offlineFlag: this.data.onlineFlag.includes(1) ? 1 : 0,
          rangeType: this.data.rangeType,
          showTitle: this.data.showTitle,
          usedDes: this.data.usedDes,
          timeLimit: this.data.timeLimit,
          startTime:
            typeof this.data.startTime === "object"
              ? dateFormat(this.data.startTime, "yyyy-MM-dd hh:mm:ss")
              : this.data.startTime,
          endTime:
            typeof this.data.endTime === "object"
              ? dateFormat(this.data.endTime, "yyyy-MM-dd hh:mm:ss")
              : this.data.endTime,
          applicateNum: this.data.applicateNum,
          limitNum: this.data.limitNum,
          warningNum: this.data.warningNum,
          expirationNotice: this.data.expirationNotice,
          smsFlag: this.data.smsFlag,
          pushFlag: this.data.pushFlag,
          smsDes: this.data.smsDes,
          relativeTime: this.data.relativeTime,
          applyName: this.data.applyName,
          couponsCostDtos: this.data.couponsCostDtos,
          // 20200811
          // 资讯张宇飞 shopLimit目前都是1
          // usingId取商户id
          couponsUsingRangeDtos: [
            { shopLimit: 1, usingId: this.data.currentUsingId },
          ],
        };

        const loading = this.$loading({
          lock: true,
          text: "请稍等...",
        });

        addCoupon(params)
          .then((res) => {
            loading.close();
            if (res.code === 200) {
              this.$message({
                message: "保存成功!",
                type: "success",
              });
              this.dialogVisible = false;
              this.$emit('save', {
                  key: 'success'
              });
            } else {
              this.$message({
                showClose: true,
                message: res.message,
                type: "error",
              });
            }
          })
          .catch((e) => {
            this.$message({
              showClose: true,
              message: "创建优惠券过程中出现问题!",
              type: "error",
            });
          });
      });
    },
    /**
     * 编辑批次时的保存操作
     */
    save() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;

        const params = {
          provider: this.data.provider,
          providedType: this.data.providedType,
          batchName: this.data.batchName,
          batchType: this.data.batchType,
          batchMoney: this.data.batchMoney,
          limitMoney: this.data.limitMoney,
          onlineFlag: this.data.onlineFlag.includes(0) ? 1 : 0,
          offlineFlag: this.data.onlineFlag.includes(1) ? 1 : 0,
          rangeType: this.data.rangeType,
          showTitle: this.data.showTitle,
          usedDes: this.data.usedDes,
          timeLimit: this.data.timeLimit,
          startTime:
            typeof this.data.startTime === "object"
              ? dateFormat(this.data.startTime, "yyyy-MM-dd hh:mm:ss")
              : this.data.startTime,
          endTime:
            typeof this.data.endTime === "object"
              ? dateFormat(this.data.endTime, "yyyy-MM-dd hh:mm:ss")
              : this.data.endTime,
          applicateNum: this.data.applicateNum,
          limitNum: this.data.limitNum,
          warningNum: this.data.warningNum,
          expirationNotice: this.data.expirationNotice,
          smsFlag: this.data.smsFlag,
          pushFlag: this.data.pushFlag,
          smsDes: this.data.smsDes,
          relativeTime: this.data.relativeTime,
          applyName: this.data.applyName,
          couponsCostDtos: this.data.couponsCostDtos,
          // 20200811
          // 资讯张宇飞 shopLimit目前都是1
          // usingId取商户id
          couponsUsingRangeDtos: [
            { shopLimit: 1, usingId: this.data.currentUsingId },
          ],
        };

        const loading = this.$loading({
          lock: true,
          text: "请稍等...",
        });

        editCoupon(this.couponId, params).then((res) => {
          loading.close();
          if (res.code === 200) {
            this.$message({
              message: "保存成功!",
              type: "success",
            });
            this.dialogVisible = false;
            this.$emit('save', {
                key: 'success'
            });
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error",
            });
          }
        });
      });
    },
    /**
     * 获取优惠券批次详情
     */
    getCouponDetail(cb) {
      const loading = this.$loading({
        lock: true,
        text: "请稍等...",
      });
      getCouponDetail(this.couponId).then((res) => {
        loading.close();
        cb && cb();
        if (res.code === 200) {
          const result = res.result;
          const data = this.data;
          data.applyName = result.applyName;
          data.provider = result.provider;
          data.providedType = result.providedType;
          data.batchName = result.batchName;
          // data.couponsCostDtos.type = result.
          data.batchType = result.batchType;
          data.batchMoney = result.batchMoney;
          data.limitMoney = result.limitMoney ? result.limitMoney : 0;

          // 场景限制
          // data.onlineFlag = [result.onlineFlag];
          let array = [];
          if (result.onlineFlag === 1) {
            array.push(0);
          }
          if (result.offlineFlag === 1) {
            array.push(1);
          }
          data.onlineFlag = array;

          // 前端展示标题
          data.showTitle = result.showTitle;
          data.usedDes = result.usedDes;
          data.timeLimit = result.timeLimit;
          // debugger;
          // 绝对日期
          if (data.timeLimit === 0) {
            data.startTime = result.startTime;
            data.endTime = result.endTime;
            const startTime = this.data.startTime
              ? new Date(this.data.startTime.replace(/-/g, "/"))
              : "";
            const endTime = this.data.endTime
              ? new Date(this.data.endTime.replace(/-/g, "/"))
              : "";
            data.time = [startTime, endTime];
          }

          // 申请数量
          data.applicateNum = result.applicateNum;
          // 每人最大可领取数量
          data.limitNum =
            result.limitNum === null ? undefined : result.limitNum;
          // 预警数量
          data.warningNum =
            result.warningNum === null ? undefined : result.warningNum;
          // 是否到期预警
          data.expirationNotice = result.expirationNotice;
          // 到期预警发短信flag(0 不发短信 1发短信)
          data.smsFlag = result.smsFlag;
          // 到期提醒是否发送appPush（0 不发生 1发送）
          data.pushFlag = result.pushFlag;
          // 短信内容
          data.smsDes = result.smsDes;
          data.relativeTime = result.relativeTime;
          // 0-全平台 1-其他 可选App或H5
          data.rangeType = result.rangeType;
          data.currentUsingId = result.usingId;
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      });
    },
    /**
     * 添加
     */
    add() {
      this.viewType = "add";
      this.dialogVisible = true;
      debugger;
      if (this.$refs.form) {
          this.$refs.form.resetFields();
          this.$refs.form.clearValidate();
      }
    },

    /**
     * 编辑
     */
    edit(couponId,status) {
      debugger;
      this.couponId = couponId;
      this.status = status;
      this.viewType = 'edit';
      if (this.$refs.form) {
          this.$refs.form.resetFields();
          this.$refs.form.clearValidate();
      }
      this.getCouponDetail(() => {
        this.dialogVisible = true;
      });
    },

    /**
     * 复制
     */
    copy(couponId, status) {
      this.couponId = couponId;
      this.status = status;
      this.viewType = 'copy';
      if (this.$refs.form) {
          this.$refs.form.resetFields();
          this.$refs.form.clearValidate();
      }
      this.getCouponDetail(() => {
        this.dialogVisible = true;
      });
    },

    /**
     * 查看详情
     */
    detail(couponId, status) {
      this.couponId = couponId;
      this.status = status;
      this.viewType = 'detail';
      
      if (this.$refs.form) {
          this.$refs.form.resetFields();
          this.$refs.form.clearValidate();
      }

      this.getCouponDetail(() => {
        this.dialogVisible = true;
      });
    },
  },
  created() {
    this.getMerchantList();
  },
};
</script>
<style lang="scss">
.dialogContent {
  height: 300px;
  overflow-y: scroll;
}
</style>